package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.BaseContext;
import com.itheima.constant.LoginConstant;
import com.itheima.result.Result;
import com.itheima.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@RequiredArgsConstructor
public class LoginCheckInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("X-Token");
        // 1.判断是否有令牌
        if (!StringUtils.hasText(token)) {

            return err(response);
        }

        // 2.判断令牌是否合法
        try {
            Claims body = jwtUtil.parseJWT(token);
            String userId = body.get(LoginConstant.USER_ID, String.class);
            //记录登录用户的id
            BaseContext.setLoginUserId(userId);
            return true;
        } catch (Exception e) {

            return err(response);
        }
    }

    private static boolean err(HttpServletResponse response) throws IOException {
        Result<?> error = Result.error(9997, "登陆验证失败，请重新登陆！");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().write(JSON.toJSONString(error));
        return false;
    }
}
